package com.fw.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fw.entity.*;
import com.fw.enums.OrderState;
import com.fw.enums.UserType;
import com.fw.service.*;
import com.fw.utils.JWTUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("/wholesale")
@RestController
public class WholeSaleController {
    @Resource
    IWholesalersService wholesalersService;
    @Resource
    IUserService userService;
    @Resource
    IMorderService morderService;
    @Resource
    IMeatService meatService;
    @Resource
    IMorelationService morelationService;

    /***
     * 功能描述：获取某批发市场的所有批发商
     * 直接调用wholesalerService，选择pifaid是当前批发市场的
     * @param request
     * @return
     */
    @RequestMapping("/listAllWholeSaler")
    public Result listAllWholeSaler(HttpServletRequest request){
        String pifauid = JWTUtils.getUserId(request.getHeader("token"));
        Map<String, Object> m = new HashMap<>();
        m.put("pifauid", pifauid);
        List<Wholesalers> wholesalers = wholesalersService.listByMap(m);
        return new Result(wholesalers, "获取该批发市场所有订单成功", "000000");
    }

    /***
     * 功能描述：对某批发商进行备案
     * 限制名称不能重复
     * 1.查看库中是否有重复数据
     * 2.插入数据
     * @param wname
     * @param request
     * @return
     * @throws MyException
     */
    @RequestMapping("/addWholeSaler")
    public Result addWholeSaler(@RequestParam String wname,
                                HttpServletRequest request) throws MyException {
        if(wname.equals(""))
            throw new MyException("批发商名称不能为空", "040401");
        String pifauid = JWTUtils.getUserId(request.getHeader("token"));
        Integer uid = Integer.parseInt(pifauid);
        //判断批发商名称是否重复
        Map<String, Object> m = new HashMap<>();
        m.put("pifauid", pifauid);
        m.put("wname", wname);
        List<Wholesalers> wholesalers = wholesalersService.listByMap(m);
        if(!wholesalers.isEmpty())//不为空
            throw new MyException("该批发商名称重复", "040202");
        //插入数据
        Wholesalers wholesaler = new Wholesalers(null, uid, wname, new Date());
        wholesalersService.save(wholesaler);
        return new Result(null, "批发商备案成功", "000000");
    }

    /***
     * 功能描述：获取所有待进场订单
     *
     * @param request
     * @return
     * @throws MyException
     */
    @RequestMapping("/listMeatInOrder")
    public Result listMeatInOrder(HttpServletRequest request) {
        String userid = JWTUtils.getUserId(request.getHeader("token"));
        Map<String, Object> m = new HashMap<>();
        m.put("obuyuid", userid);
        List<Morder>morderList = morderService.listByMap(m);
        String[] types = {"里脊", "排骨", "五花肉", "内脏", "肘子"};
        for (Morder morder:
                morderList) {
            Map<String, Object> ans = new HashMap<>();
            Map<String, Object> searchMap = new HashMap<>();
            searchMap.put("oid", morder.getOid());
            List<Morelation> morelations = morelationService.listByMap(searchMap);
            List<Integer> ids = new ArrayList<>();
            for (Morelation morelation :
                    morelations) {
                ids.add(morelation.getMid());
            }
            System.out.println(morelations);
            System.out.println(ids);
            List<Meat> meatList = meatService.listByIds(ids);
            int []nums = {0,0,0,0,0};
            for (Meat meat :
                    meatList) {
                if(meat.getMtype().equals(types[0]))
                    nums[0]++;
                else if(meat.getMtype().equals(types[1]))
                    nums[1]++;
                else if(meat.getMtype().equals(types[2]))
                    nums[2]++;
                else if(meat.getMtype().equals(types[3]))
                    nums[3]++;
                else if(meat.getMtype().equals(types[4]))
                    nums[4]++;
            }
            for(int i = 0; i < 5; i++){
                ans.put(types[i], nums[i]);
            }
            morder.setM(ans);
            morder.setOsellname(userService.getById(morder.getOselluid()).getUname());
        }
        return new Result(morderList, "获取所有订单成功", "000000");
    }

    /***
     * 功能描述：猪肉进场
     * 1.判断格式
     * 2.查找订单
     * 3.判断相关内容
     * 4.更改订单状态
     * 5.更改猪肉状态(这里并不用更改猪肉状态，在生成订单时就都填写好了)
     * @param oid
     * @param request
     * @return
     * @throws MyException
     */
    @RequestMapping("/meatIn")
    public Result meatIn(@RequestParam String oid,
                         HttpServletRequest request) throws MyException {
        //判断输入
        if (oid.equals(""))
            throw new MyException("订单号不能为空", "040401");
        String userid = JWTUtils.getUserId(request.getHeader("token"));
        //查找订单号对应订单
        Map<String, Object> m = new HashMap<>();
        m.put("oid", oid);
        List<Morder> morderList = morderService.listByMap(m);
        //订单是否存在
        if(morderList.isEmpty())
            throw new MyException("该订单不存在", "040405");
        Morder morder = morderList.get(0);
        System.out.println(morder);
        System.out.println(userid);
        //订单购买者是否是该批发市场
        if(!morder.getObuyuid().toString().equals(userid))
            throw new MyException("订单不属于该批发市场", "040404");
        //判断订单状态
        if(morder.getOstate().equals(OrderState.START.getValue()))
            throw new MyException("该订单未出场", "040403");
        if(morder.getOstate().equals(OrderState.FINISH.getValue()))
            throw new MyException("该订单已入场", "040402");
        //设置订单相关属性
        morder.setOstate(OrderState.FINISH.getValue());
        morder.setIndate(new Date());
        morderService.saveOrUpdate(morder);
        //更改猪肉状态
        return new Result(null, "该订单猪肉进场成功", "000000");
    }

    /***
     * 功能描述：猪肉自动分配
     * 1.获取订单，判断订单相关状态
     * 2.
     * @param oid
     * @param request
     * @return
     * @throws MyException
     */
    @RequestMapping("/meatAutoDivide")
    public Result meatAutoDivide(@RequestParam String oid,
                                 HttpServletRequest request) throws MyException {
        if(oid.equals(""))
            throw new MyException("订单id不能为空", "040501");
        String userid = JWTUtils.getUserId(request.getHeader("token"));
        Map<String, Object> m = new HashMap<>();
        m.put("oid", oid);
        List<Morder> morderList = morderService.listByMap(m);
        //判断订单相关状态
        if(morderList.isEmpty())
            throw new MyException("该订单不存在", "040502");
        Morder morder = morderList.get(0);
        System.out.println(morder.getObuyuid() + " " + userid);
        if(!morder.getObuyuid().toString().equals(userid))
            throw new MyException("订单不属于该批发市场", "040503");
        if(!morder.getOstate().equals(OrderState.FINISH.getValue()))
            throw new MyException("该订单未入场", "040504");
        m.clear();
        m.put("mpath2", oid);
        m.put("mowneruid", userid);
        List<Meat> meatList = meatService.listByMap(m);
        if(meatList.get(0).getMpath3() != null)
            throw new MyException("该订单已分发", "040505");
        //获取该批发市场所有批发商
        m.clear();
        m.put("pifauid", userid);
        List<Wholesalers> wholesalers = wholesalersService.listByMap(m);
        int wnum = wholesalers.size();
        if(wnum == 0)
            throw new MyException("本批发市场不存在批发商", "040506");
        int num = 0;
        for (Meat meat :
                meatList) {
            if(num == wnum)
                num = 0;
            meat.setMpath3(wholesalers.get(num).getWid());
            num++;
        }
        meatService.saveOrUpdateBatch(meatList);
        return new Result(null, "猪肉自动分发成功", "000000");
    }

    /***
     * 功能描述：猪肉出场登记
     * 1.判断批发商是否属于批发市场
     * 2.计算该批发商所拥有的全部猪肉数量
     * 3.
     * @param rid,wid,wnumarray,request
     * @return
     */
    @RequestMapping("/meatRegister")
    public Result meatRegister(@RequestParam String rid,
                               @RequestParam String wid,
                               @RequestParam String mnumarray,
                               HttpServletRequest request) throws MyException {
        //转化数组，判断格式
        JSONArray numarray = JSONUtil.parseArray(mnumarray);
        List<Integer> nums = numarray.toList(Integer.TYPE);
        System.out.println(nums);
        if(nums.size() < 5)
            throw new MyException("猪肉数量格式错误", "040704");
        if(wid.isEmpty())
            throw new MyException("批发商id不能为空", "040705");
        //判断该零售商
        String userid = JWTUtils.getUserId(request.getHeader("token"));
        Map<String, Object> m = new HashMap<>();
        m.put("uid", rid);
        List<User> users = userService.listByMap(m);
        if(users.isEmpty())
            throw new MyException("该零售商不存在", "040706");
        User user = users.get(0);
        if(!user.getUtype().equals(UserType.RETAILER.getValue()))
            throw new MyException("该用户不是零售商", "040707");
        //判断批发商
        m.clear();
        m.put("wid", wid);
        List<Wholesalers> wholesalers = wholesalersService.listByMap(m);
        if(wholesalers.isEmpty())
            throw new MyException("批发商不存在", "040701");
        Wholesalers wholesaler = wholesalers.get(0);
        if(wholesaler.getPifauid().equals(userid))
            throw new MyException("该批发商不属与本批发市场", "040702");
        //计算数量
        String[] types = {"里脊", "排骨", "五花肉", "内脏", "肘子"};
        m.clear();
        m.put("mpath3", wid);
        m.put("mownertype", UserType.WHOLESALE.getValue());
        List<List<Meat>> meatList = new ArrayList<>();
        for(int i = 0; i < 5; i++){
            m.remove("mtype");
            m.put("mtype", types[i]);
            List<Meat> meats = meatService.listByMap(m);
            if(meats.size() < nums.get(i))
                throw new MyException(types[i]+"类型猪肉数量不满足", "040703");
            meatList.add(meats);
        }
        //创建订单
        Integer ruid = Integer.parseInt(rid);
        Morder morder = new Morder(null, Integer.parseInt(userid),
                               ruid , OrderState.START.getValue(), new Date(), null, null, null);
        morderService.save(morder);
        //更新猪肉
        int j = 0;
        for (List<Meat> meats :
                meatList) {
            List<Morelation> morelations = new ArrayList<>();
            for(int i = 0; i < nums.get(j); i++){
                Meat meat = meats.get(i);
                meat.setMpath4(morder.getOid());
                meat.setMownertype(UserType.RETAILER.getValue());
                meat.setMowneruid(ruid);
                morelations.add(new Morelation(null, morder.getOid(), meat.getMid()));
            }
            j++;
            meatService.saveOrUpdateBatch(meats);
            morelationService.saveOrUpdateBatch(morelations);
        }
        return new Result(null, "猪肉出场登记成功", "000000");
    }

}
